package com.home.security.browser.interceptor;

import com.home.base.core.context.BaseContextHandler;
import com.home.base.core.framework.enums.ResultCodeEnum;
import com.home.common.utils.json.JsonUtils;
import com.home.security.browser.shiro.ShiroUtils;
import com.home.common.model.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Description: Shiro 拦截器
 * 获取用户信息,可以直接用过 ShiroUtils.getUserInfo()来获取
 * 这里将用户信息添加到 BaseContextHandler 里面,方便后期框架升级
 * <p>
 * Created by 王大宸 on 2020-11-12 13:57
 * Created with IntelliJ IDEA.
 */
public class BrowserInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(BrowserInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        try {
            String method = request.getMethod();
            // OPTIONS 直接通过
            if (HttpMethod.OPTIONS.matches(method)) {
                return super.preHandle(request, response, handler);
            }

            CurrentUser userInfo = ShiroUtils.getUserInfo();

            if (null == userInfo) {
                return super.preHandle(request, response, handler);
            }

            BaseContextHandler.setAccount(userInfo.getUsername());
            BaseContextHandler.setName(userInfo.getName());
            BaseContextHandler.setUserId(userInfo.getId());
            BaseContextHandler.setAvatar(userInfo.getAvatar());
            BaseContextHandler.setUserType(userInfo.getType());
            return super.preHandle(request, response, handler);
        } catch (Exception e) {
            logger.error("用户认证错误：", e);
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(getMessage(ResultCodeEnum.CLIENT_TOKEN_EXCEPTION.getStatus(), e.getMessage()));
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) {
    }

    private String getMessage(int status, String msg) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", status);
        map.put("msg", msg);
        map.put("data", null);
        map.put("success", false);
        return JsonUtils.toJson(map);
    }
}
